package wordUtil.docExport;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;

public class Pictrue {
	private int width;
	private int height;
	private int type;
	private byte[] data;
	private File file;

	/**
	 * @param file 图片文件
	 */
	public Pictrue(File file) throws IOException{
		this.file = file;
		this.data = inputStream2ByteArray(new FileInputStream(file));
		this.type = getPictureType(file);
		BufferedImage image = ImageIO.read(file);
		this.width = image.getWidth();
		this.height = image.getHeight();
	}

	/**
	 * @param file 图片文件
	 * @param width 宽度
	 * @param height 高度
	 */
	public Pictrue(File file,int width,int height) throws FileNotFoundException{
		this.file = file;
		this.data = inputStream2ByteArray(new FileInputStream(file));
		this.type = getPictureType(file);
		this.width = width;
		this.height = height;
	}
	
	private int getPictureType(File file){
		String name = file.getName();
		return getPictureType(name.substring(name.lastIndexOf('.')));
	}

	/**
	 * 根据图片类型，取得对应的图片类型代码
	 * @param picType
	 * @return int
	 */
	private int getPictureType(String picType){
		int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
		if(picType != null){
			if(picType.equalsIgnoreCase("png")){
				res = CustomXWPFDocument.PICTURE_TYPE_PNG;
			}else if(picType.equalsIgnoreCase("dib")){
				res = CustomXWPFDocument.PICTURE_TYPE_DIB;
			}else if(picType.equalsIgnoreCase("emf")){
				res = CustomXWPFDocument.PICTURE_TYPE_EMF;
			}else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){
				res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
			}else if(picType.equalsIgnoreCase("wmf")){
				res = CustomXWPFDocument.PICTURE_TYPE_WMF;
			}
		}
		return res;
	}
	
	/**
	 * 将输入流中的数据写入字节数组
	 * @param in
	 * @return
	 */
	private byte[] inputStream2ByteArray(InputStream in){
		byte[] byteArray = null;
		try {
			int total = in.available();
			byteArray = new byte[total];
			in.read(byteArray);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				in.close();
			} catch (Exception e2) {
				System.out.println("关闭流失败");
			}
		}
		return byteArray;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public int getType() {
		return type;
	}

	public byte[] getData() {
		return data;
	}

	public File getFile() {
		return file;
	}
}
